package com.jqr.activity.myschool.https
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable

import androidx.lifecycle.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData

import com.jqr.activity.myschool.App

import com.jqr.activity.myschool.https.models.Articles
import com.jqr.activity.myschool.https.models.Data
import com.jqr.activity.myschool.utils.EasyDataStore
import com.jqr.activity.myschool.utils.EasyDate
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.Dispatchers
import java.lang.Exception
import javax.inject.Inject

import kotlin.coroutines.CoroutineContext

open class BaseRepository{
    fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) =
        liveData(context) {
            val result = try {
                block()
            } catch (e: Exception) {
                Result.failure(e)
            }
            //通知数据变化
            emit(result)
        }
}

@ViewModelScoped
class ArticleRepository @Inject constructor() : BaseRepository() {

    private val TAG="ArticleRepository"

    private  val REQUEST_TIMESTAMP="requestTimestamp_news"
    companion object{
        lateinit var articles:Articles
    }
    fun getAllArticle(isRefresh:Boolean) = fire(Dispatchers.IO) {
        val now:Long=EasyDate.timestamp
        val  old:Long=EasyDataStore.getData(REQUEST_TIMESTAMP,1649049670500)
        if(isRefresh&&now <= old){
            Log.d(TAG,"从本地数据库获取数据")
            articles=getLocalForArticles()

        }
        else{
            Log.d(TAG,"从网络获取数据")
            articles = HttpRequest.getAllArticles()
            System.out.println(articles)
            saveArticles(articles)
        }

        if (articles.success) {
            Result.success(articles)
        } else {
            Result.failure(RuntimeException("articles response code is ${articles.code} msg is ${articles.msg}"))
        }
    }

    /**
     * 保存到本地数据库
     */
    private suspend fun saveArticles(articles: Articles) {
        Log.d(TAG, "saveNews: 保存到本地数据库")
        EasyDataStore.putData(REQUEST_TIMESTAMP, EasyDate.getMillisNextEarlyMorning())
        App.db.articleDao().deleteAll()
        articles.data.data?.let {
            App.db.articleDao().insertAll(it)
        }

    }

    /**
     * 从本地数据库中加载
     */
    private suspend fun getLocalForArticles() = Articles(
        "成功",
        code = 1,
        success = true,
        data = Data(App.db.articleDao().getAll())
        )
}



